"use client";

import { usePathname } from "next/navigation";
import { PropsWithChildren, useEffect, useState } from "react";
import NotFound from "../not-found";
import { useSelector } from "react-redux";
import { RootState } from "../redux/store";
import Loading from "../loading";
import Login from "../login/page";
import { RouterItem } from "../redux/reducer";
import { useCheckPermission } from "../hooks/useCheckPermission";

export default function AccessLayout({ children }: PropsWithChildren) {
  const pathname = usePathname();
  const roleList = useSelector((state: RootState) => state.routesList.router);
  const [storedRole, setStoredRole] = useState<RouterItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  // 检查权限
  const hasPermission = useCheckPermission(pathname, roleList.length ? roleList : storedRole);

  useEffect(() => {
    async function initPermissions() {
      try {
        // 如果 Redux 中没有权限数据，尝试从 localStorage 读取
        if (!roleList.length) {
          const localStorageData = localStorage.getItem("role");
          if (localStorageData) {
            const parsed = JSON.parse(localStorageData);
            if (parsed && Array.isArray(parsed.router)) {
              setStoredRole(parsed.router);
            }
          }
        }
      } catch (error) {
        console.error("Error loading permissions from localStorage:", error);
      } finally {
        setIsLoading(false);
      }
    }

    initPermissions();
  }, [roleList.length]);

  if (isLoading) {
    return <Loading />;
  }

  if (!roleList.length && !storedRole.length) {
    return <Login />;
  }

  if (!hasPermission) {
    return <NotFound />;
  }

  return <>{children}</>;
}